package com.fate.securecheckplatform.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 *
 */
public class DownLoadApk {
    private static DownLoadApk mDownloadApk;
    private final String BASE_FOLDER = Environment
            .getExternalStorageDirectory()
            + File.separator
            + "SecureCheckPlatform"
            + File.separator;
    private final String updateFolder = BASE_FOLDER + "update"
            + File.separator;
    private Context context;
    private File apk_path;

    public static DownLoadApk getInstant() {

        if (mDownloadApk == null)
            mDownloadApk = new DownLoadApk();
        return mDownloadApk;
    }

    public void downloadAPK(String url, Context context) {
        this.context = context;
        if (url == null)
            // 不下载更新
            return;
        new DownloadTask().execute(url);
    }

    @SuppressLint("StaticFieldLeak")
    private class DownloadTask extends AsyncTask<String, Integer, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            File file = new File(updateFolder);
            if (!file.exists())
                file.mkdirs();
            try {
                apk_path = new File(file.getAbsolutePath() + File.separator
                        + "SecureCheckPlatform.apk");
                apk_path.createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        @Override
        protected Void doInBackground(String... params) {
            try {
                URL url = new URL(params[0]);
                InputStream is = url.openStream();
                FileOutputStream fos = new FileOutputStream(apk_path);
                byte[] buffer = new byte[1024];
                int len;
                int progress = 0;
                while ((len = is.read(buffer)) != -1) {
                    progress += len;
                    publishProgress(progress);
                    fos.write(buffer, 0, len);
                }
                is.close();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (apk_path.exists()) {
                installAPK();
            }
        }

        public void installAPK() {


            Intent install = new Intent(Intent.ACTION_VIEW);
            //适配7.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 大于 8.0
                install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", apk_path);
                install.setDataAndType(contentUri, "application/vnd.android.package-archive");
                context.startActivity(install);// 安装
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // 5.1-7.0 并未适配6.0 的权限申请
                install.setDataAndType(Uri.fromFile(apk_path), "application/vnd.android.package-archive");
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(install);// 安装
            }

        }


        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

    }
}
